var xhr;

var NULL_EMAIL = 1;         // no email supplied
var NULL_PWD = 2;           // no password supplied
var EMAIL_NT_REG = 3;       // no records found
var WRONG_PWD = 4;          // password mismatch
var INVALID_EMAIL = 5;      // email syntax is worng
var INACTIVE_ACC = 6;       // inactive account
var SYS_ERR = 7;            // system error
/*****************************************************************************/
function validateLogin() {
    
    /* create xhr */
    if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest;
    }

    /* build query string */
    var strEmail = document.getElementById("txtEmail").value;
    var strPassword = document.getElementById("txtPassword").value;
    var strRememberMe = document.getElementById("chkRememberMe").checked;
    var strQuery = "txtEmail=" + strEmail + "&txtPassword=" + strPassword + "&chkRememberMe=" + strRememberMe;
    
    /* setup xhr */
    xhr.open("POST", "CustomerLoginServlet?timeStamp=" + new Date().getTime(), true);
    xhr.onreadystatechange = handleLoginResponse;
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    
    xhr.send(strQuery);

    /* processing... */
    document.getElementById("divError").style.display = "block";
    document.getElementById("divError").innerHTML = "Processing...";
}
/*****************************************************************************/
function handleLoginResponse(){

    if (xhr.readyState != 4) return;
  
    if (xhr.status != 200) return;
    
    /* handle the response */
    var xhresponse = xhr.responseXML;
    var nodError = xhresponse.getElementsByTagName("ErrorCode");
    var divError = document.getElementById("divError");

    if (nodError.length > 0) {
        var iErrorCode = parseInt(nodError[0].firstChild.nodeValue);
        switch (iErrorCode) {
            case 1:
                divError.innerHTML = "Oops! You missed out the email.";
                break;
            case 2:
                divError.innerHTML = "Oops! You missed out the password.";
                break;
            case 3:
                divError.innerHTML = "This email is not registered. Are you trying to register an account with that? If yes, click <a href='register.html'>here</a>.";
                break;            
            case 4:
                divError.innerHTML = "Password in incorrect. Did you forget your password. You can recover it <a href='recover.html'>here</a>";
                break;
            case 5:
                divError.innerHTML = "This email is invalid. Have you mistyped";
                break;
            case 6:
                divError.innerHTML = "This account is not yet activated Please login to your email to activate this account.";
                break;
            case 7:
                divError.innerHTML = "We are currently experiencing problems on our system. Please try to login later.";
        }
    } else {
        divError.innerHTML = "";
        divError.style.display = "none";
        
        /* redirects and display welcome message for 3 sec */
        setTimeout("window.location = 'index.html';", 2500);
        displayPopup("Welcome! " + getCookie("FirstName") + ", you are now logged in", "center", 2500);
    }  
}
/*****************************************************************************/
function checkLogin() {

    //document.getElementById("lstManager").style.display = "none";
    
    var aLogin = document.getElementById("aLogin");
    var aLogout = document.getElementById("aLogout");
    var divCustMenu = document.getElementById("divCustMenu");
    var divWelcome = document.getElementById("divWelcome");

    var strEmployeeID = getCookie("EmployeeID")
    var strCustomerID = getCookie("CustomerID");

    if (strEmployeeID == "" && strCustomerID == "") { // no user logged in, so display login
        if (aLogout && !aLogin) {
            aLogin = createLogin();
            divCustMenu.replaceChild(aLogin, aLogout);
        }
        divWelcome.innerHTML = "New customer? <a href=register.html>Register here</a>";
        
        return false;
    }
    else { // some user is logged in, so display logout
        if (aLogin && !aLogout) {
            aLogout = createLogout();
            divCustMenu.replaceChild(aLogout, aLogin);
        }
        /* manager tasks */
        if (strEmployeeID != "")
            showManagerTasks();
        else
            hideManagerTasks();

        divWelcome.innerHTML = "Hello, " + getCookie("FirstName");
        return true;
    }   
}
/*****************************************************************************/
function logout() {
   
    var strFirstName = getCookie("FirstName");
    var strUserLevel = getCookie("UserLevel");
    var strCustomerID = getCookie("CustomerID");
    var strEmployeeID = getCookie("EmployeeID");
    
    if (strFirstName!="") {
    
        /* delete the cookies */ 
        document.cookie = "FirstName=" + strFirstName + "; expires=Thu, 01-Jan-1970 00:00:01 GMT";
        document.cookie = "UserLevel=" + strUserLevel + "; expires=Thu, 01-Jan-1970 00:00:01 GMT";
        document.cookie = "CustomerID=" + strCustomerID + "; expires=Thu, 01-Jan-1970 00:00:01 GMT";
        document.cookie = "EmployeeID=" + strEmployeeID + "; expires=Thu, 01-Jan-1970 00:00:01 GMT";

        /* remove logout, hide welcome message and display login */
        var aLogin = createLogin();
        var aLogout = document.getElementById("aLogout");
        var divWelcome = document.getElementById("divWelcome");
        var divCustmenu = document.getElementById("divCustMenu");

        divCustmenu.replaceChild(aLogin, aLogout);

        divWelcome.innerHTML = "New customer? <a href=register.html>Register here</a>";
        
        /* remove manager tasks */
        hideManagerTasks();
        
        /* display logout message for 2.5 sec*/
        setTimeout("needsRedirect();", 2500);
        displayPopup("Thank you, " + strFirstName + "! You are now logged out", "center", 2500);
    }
}
/*****************************************************************************/
/* builds the login link */
function createLogin() {

    var aLogin = document.createElement("a");
    
    aLogin.setAttribute("id", "aLogin");
    aLogin.setAttribute("href", "login.html");
    aLogin.appendChild(document.createTextNode("Login"));
    
    return aLogin;
}
/*****************************************************************************/
/* builds the logout link */
function createLogout() {

    var aLogout = document.createElement("a");
   
    aLogout.setAttribute("id", "aLogout");
    aLogout.setAttribute("href", "javascript:logout()");
    aLogout.appendChild(document.createTextNode("Logout"));
   
    return aLogout;
}
/*****************************************************************************/
function needsRedirect() {
    if (window.location.pathname == "/CelestialApp/particulars.html")
        window.location = "index.html";
}
/*****************************************************************************/
function showManagerTasks() {
    
    var li = document.getElementById("liManagerTasks");
    if (li != null) return;
    
    /* list element */
    li = document.createElement("li");
    li.setAttribute("id", "liManagerTasks");
    
    /* image element */
    var img = document.createElement("img");
    img.setAttribute("src", "images/manager_tasks.png");
    
    /* link element */
    var a = document.createElement("a");
    a.setAttribute("href", "employees.html");

    /* text node */
    var txt = document.createTextNode(" Manager");

    a.appendChild(txt);
    li.appendChild(img);
    li.appendChild(a);

    var ulNavBar = document.getElementById("ulNavBar");
    ulNavBar.appendChild(li);
}
/*****************************************************************************/
function hideManagerTasks() {
    
    var liManagerTasks = document.getElementById("liManagerTasks");

    if (liManagerTasks == null) return;

    var ulNavBar = document.getElementById("ulNavBar");
    ulNavBar.removeChild(liManagerTasks);
}